#include "drv_usart.h"
#include "driver_LED.h"

uint8_t order[10] = {0};

void drv_usart6_init(void)
{
	 GPIO_InitTypeDef GPIO_InitStruct;
	 USART_InitTypeDef USART_InitStruct;
	 NVIC_InitTypeDef NVIC_InitStruct;
	 

	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOG,ENABLE);//使能gpio端口时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6, ENABLE);// 使能 USART6 外设时钟

	GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9|GPIO_Pin_14;//选择要配置的引脚
	GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;//复用
	GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;//推挽
	GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;//上拉

	GPIO_Init(GPIOG,& GPIO_InitStruct);
	

	GPIO_PinAFConfig(GPIOG,GPIO_PinSource9,GPIO_AF_USART6);
	GPIO_PinAFConfig(GPIOG,GPIO_PinSource14,GPIO_AF_USART6);
	USART_InitStruct.USART_BaudRate = 115200;//波特率：115200
	USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStruct.USART_Mode = USART_Mode_Rx|USART_Mode_Tx;//同时使能接收和发送
	USART_InitStruct.USART_Parity = USART_Parity_No;//无校验
	USART_InitStruct.USART_StopBits = USART_StopBits_1;//停止位：1位（标准配置）
	USART_InitStruct.USART_WordLength = USART_WordLength_8b;//数据位8位
	USART_Init(USART6,& USART_InitStruct);//应用配置到usart6外设

	USART_ITConfig(USART6,USART_IT_RXNE,ENABLE);
	//配置usart6中断优先级
	NVIC_InitStruct.NVIC_IRQChannel = USART6_IRQn;//指定中断通道：usart6中断
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;//抢占优先级
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;//子优先级
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;//使能该中断通道

	NVIC_Init(&NVIC_InitStruct);
	
	USART_ClearFlag(USART6,USART_FLAG_TC);//清除发送完成标志位：初始化后确保无残留标志，避免误触发首次发送逻辑
	USART_Cmd(USART6,ENABLE);//使能usart6外设，最后一步开启串口，确保所有配置生效后启动通信
}

int fputc(int ch,FILE *f)
{
	USART_SendData(USART6,ch);
	while(USART_GetFlagStatus(USART6,USART_FLAG_TC)==RESET);
	USART_ClearFlag(USART6,USART_FLAG_TC);//清除发送完成标志：显示清除标志，确保下次发送检测准确
	return ch;
}

void usart6_send(uint8_t *str)
{
	while(*str)//循环至'\0'
		{
			USART_SendData(USART6,*str);
			while(USART_GetFlagStatus(USART6,USART_FLAG_TC)==RESET);//检查usart的发送完成标志位, 当标志位为RESET（未置位）时，持续等待
			str++;
		}
}

void usart6_compare(void)
{
	if(strcmp((char*)order,"led open")==0)
		{
			drv_led_open();
			usart6_send((uint8_t*)"led opened");
		}
	else if(strcmp((char*)order,"led close")==0)
		{
			drv_led_close();
			usart6_send((uint8_t*)"led closed");
		}
	memset(order,0,10);
}

